<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Http;
use fast\Random;
use fast\Tree;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Hook;

class Order extends Frontend
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = 'mall';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            $expire = 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });

        //获取brand BEGIN
        $mapBrand = [
            'switch' => 1,
        ];
        $brandData = model('app\common\model\Brand')
            ->field('id,name,image')
            ->where($mapBrand)
            ->order('top_switch desc,weigh asc')
            ->select();

        //$brand = addWebSiteUrl($brandData, ['image']);
        $this->view->assign('brand',$brandData);
        //获取brand END

        //cart BEGIN
        $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
        $this->view->assign('cart',$cart);
        //cart END

        //获取商品cate BEGIN
        $tree = Tree::instance();
        $tree->init(collection( model('app\common\model\Category')->where('type','goods')->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $category = $tree->getTreeArray(0);
        $this->view->assign('category',$category);
        //获取商品cate END
    }

    public function index()
    {
        $payType = $this->request->request('payType','');
        $this->assignconfig('payType',$payType);
        $this->assignconfig('paytm_api',config('site.paytm_api'));

        //获取订单 BEGIN
        $map = [
            'user_id' => $this->auth->id,
        ];

        $orderList = model('app\common\model\Order')
            //->with('orderproducts')
            ->where($map)
            ->order('updatetime desc')
            ->paginate(10);
        //$goods = addWebSiteUrl($goodsData, ['image']);
        $this->view->assign('orderList',$orderList);
        $page = $orderList->render();
        $this->view->assign('page', $page);
        //获取订单 END

        return $this->view->fetch();
    }

    public function checkout()
    {
        $data = [];
        $num = 0;
        $total_price = 0;
        $list = [];
        $type = 'now';
        if ($this->request->isPost()){
            $products_id = $this->request->post('products_id');
            $num = $this->request->post('num');

            $result = model('app\common\model\Products')->getProductInfo($products_id);
            $data = $result['data'];
            $total_price = number_format($data['price'] * $num,2);

            $list = [
                [
                    'data'  => $data,
                    'num'   => $num,
                    'total_price' => $total_price,
                ]
            ];

        } elseif ($this->request->request('type') == 'cart'){
            $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];

            foreach ($cart as $products_id => $v){
                $num = $v['num'];
                $result = model('app\common\model\Products')->getProductInfo($products_id);
                $data = $result['data'];
                $total_price += $data['price'] * $num;

                $list[] = [
                    'data'  => $data,
                    'num'   => $num,
                    'total_price' => number_format($data['price'] * $num,2),
                ];
            }
            $total_price = number_format($total_price,2);
            $type = 'cart';
        }
//        echo '<pre>';
//        var_dump($list);exit();
        $this->view->assign('list', $list);
        $this->view->assign('total_price',$total_price );
        $this->view->assign('type', $type);

        return $this->view->fetch();
    }

    public function shipping()
    {
        $total_price = 0;
        $list = [];

        if ($this->request->isPost()){

            //user email
            $email = $this->request->post('email');
            $user = \app\common\model\User::get(['email' => $email]);

            if ($user) {
                $this->auth->direct($user->id);
            } else {
                //create user
                $ret = $this->auth->register($email, Random::alnum(), $email, '', []);
            }

            //address
            $this->addAddress();

            //products
            if ($this->request->post('type') == 'now'){
                $products_id = $this->request->post('products_id');
                $num = $this->request->post('num');

                $result = model('app\common\model\Products')->getProductInfo($products_id);
                $data = $result['data'];
                $total_price = number_format($data['price'] * $num,2);

                $list = [
                    [
                        'data'  => $data,
                        'num'   => $num,
                        'total_price' => $total_price,
                    ]
                ];

            } else{
                $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];

                foreach ($cart as $products_id => $v){
                    $num = $v['num'];
                    $result = model('app\common\model\Products')->getProductInfo($products_id);
                    $data = $result['data'];
                    $total_price += $data['price'] * $num;

                    $list[] = [
                        'data'  => $data,
                        'num'   => $num,
                        'total_price' => number_format($data['price'] * $num,2),
                    ];
                }
                $total_price = number_format($total_price,2);
            }
        }

        //获取收货地址
        $mapAddress = [
            'user_id' => $this->auth->id,
            'is_default' => 1,
        ];
        $address = model('app\common\model\Address')
            ->field('id,user_id,name,mobile,is_default,area,detail')
            ->where($mapAddress)
            ->find();

        $this->view->assign('list', $list);
        $this->view->assign('total_price',$total_price );
        $this->view->assign('address', $address);

        return $this->view->fetch();
    }

    public function addAddress(){
        $name = $this->request->request('addressName');
        $mobile = $this->request->request('addressMobile');
        $area = $this->request->request('addressArea');
        $detail = $this->request->request('addressDetail');
        $is_default = $this->request->request('is_default',1);

        $param = [
            'user_id'   => $this->auth->id,
            'name'      => $name,
            'mobile'    => $mobile,
            'area'      => $area,
            'detail'    => $detail,
            'is_default' => $is_default,
        ];

        Db::startTrans();
        try {
            //判断新增地址是否设置默认，更新原来的默认地址为0
            if ($is_default){
                $map = [
                    'user_id' => $this->auth->id,
                    'is_default' => 1,
                ];

                $data = [
                    'is_default' => 0,
                    'updatetime' => time(),
                ];
                model('app\common\model\Address')->where($map)->update($data);
            }
            $result = model('app\common\model\Address')->save($param);
            $address_id = model('app\common\model\Address')->getLastInsID();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return 0;
        }

        return $address_id;
    }

    public function pay()
    {
        $sn = $this->request->post('sn');
        $amount = $this->request->post('amount');

        $params = [
            'orderNo' => $sn,
            'amount'  => $amount
        ];
        $res = Http::get(config('site.paytm_api'),$params);
        $res = json_decode($res);
        if ($res){
            $this->success('','',$res);
        }else{
            $this->error();
        }
    }
}
